package com.qianfeng.vhly.youshare.adapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.qianfeng.vhly.youshare.Constants;
import com.qianfeng.vhly.youshare.R;
import com.qianfeng.vhly.youshare.model.Product;
import com.qianfeng.vhly.youshare.utils.FileCache;
import com.qianfeng.vhly.youshare.utils.ImageCache;
import com.qianfeng.vhly.youshare.utils.ImageLoader;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/2/6
 * Email: vhly@163.com
 */

/**
 * 商城核心产品列表ListView的Adapter
 */
public class StoreCoreAdapter extends BaseAdapter {

    // 用于设置ListView条目的背景
    private static int[] colors = new int[]{
            0xFFFA950A, 0xFF157FC9, 0xFF70B10F,
            0xFF907C5F, 0xFFD42749, 0xFF6A588E
    };


    private List<Product> products;

    private LayoutInflater inflater;

    public StoreCoreAdapter(Context context, List<Product> products) {
        if (context != null) {
            inflater = LayoutInflater.from(context);
        } else {
            throw new IllegalArgumentException("Context must not null");
        }
        this.products = products;
    }

    @Override
    public int getCount() {
        int ret = 0;
        if (products != null) {
            ret = products.size();
        }
        return ret;
    }

    @Override
    public Object getItem(int position) {
        Object ret = null;
        if (products != null) {
            ret = products.get(position);
        }
        return ret;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View ret = null;

        // convertView 用于复用，convertView 就是ListView滚动的时候，滑出去的View
        if (convertView != null) {
            ret = convertView;
        } else {
            ret = inflater.inflate(R.layout.item_store_core, parent, false);
        }

        ret.setBackgroundColor(colors[position % colors.length]);

        ViewHolder holder = (ViewHolder) ret.getTag();

        if (holder == null) {
            holder = new ViewHolder();
            holder.txtPosition = (TextView) ret.findViewById(R.id.item_core_position);
            holder.txtShortTitle = (TextView) ret.findViewById(R.id.item_core_short_title);
            holder.txtTitle = (TextView) ret.findViewById(R.id.item_core_title);
            holder.imgIcon = (ImageView) ret.findViewById(R.id.item_core_product_icon);

            ret.setTag(holder);
        }

        Product product = products.get(position);

        int loc = position + 1;

        String s = Integer.toString(loc);

        if (loc < 10) {
            s = "0" + s;
        }

        // 显示索引位置
        holder.txtPosition.setText(s);

        s = product.getAppGName();
        if (s == null || s.length() == 0) {
            s = product.getGoodsName();
        }

        // 显示短标题
        holder.txtShortTitle.setText(s);

        s = product.getGoodsName();
        holder.txtTitle.setText(s);

        // TODO 加载图片。
        // 设置默认图片，避免出现复用的View显示以前图片的问题。
        holder.imgIcon.setImageResource(R.drawable.product_default);

        // 获取缩略图，缩略图采用的是相对路径的形式，
        // 要想完成访问，必须要进行网址的处理
        String thumb = product.getGoodsThumb();

        if (thumb != null && thumb.length() > 0) {
            if (!thumb.startsWith("http://") && !thumb.startsWith("https://")) {
                // TODO 进行网址的处理。
                thumb = Constants.IMAGE_SERVER + thumb;
            }

            // 0. 每次进行图片下载之前，设置 ImageView的 tag
            //    异步任务检查Tag
            holder.imgIcon.setTag(thumb);

            // 进行内存缓存的检查，如果有图片，直接加载
            ImageCache imageCache = ImageCache.getInstance();

            Bitmap bitmap = imageCache.getImage(thumb);
            // 如果内存中包含图片对象 Bitmap 那么就直接设置 ImageView
            if (bitmap != null) {
                Log.d("YouShare", "Hit cache " + thumb);
                holder.imgIcon.setImageBitmap(bitmap);
            } else {
                // 不包含缓存，进行本地文件缓存的加载

                // TODO 加载本地文件内容
                FileCache fileCache = FileCache.getInstance();

                byte[] bytes = fileCache.getContent(thumb);

                if(bytes != null && bytes.length > 0){

                    Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    holder.imgIcon.setImageBitmap(bmp);

                    imageCache.putImage(thumb, bmp);

                }else {
                    // 就进行网络的加载
                    Log.d("YouShare", "Load " + thumb);
                    // 1. 开启异步任务
                    ImageLoader task = new ImageLoader(holder.imgIcon);
                    task.execute(thumb);
                }
            }
        }

        return ret;
    }


    /**
     * 避免每次进行findViewById
     */
    private static class ViewHolder {
        public TextView txtPosition;
        public TextView txtShortTitle;
        public TextView txtTitle;
        public ImageView imgIcon; // 商品图片
    }

}
